package com.zbkj.front.config;

import com.zbkj.common.result.CommonResult;
import com.zbkj.common.result.CommonResultCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Aspect
@Component
public class PreventDuplicateAspect {
    private final String PREFIX = "PREVENT_DUPLICATE";

    @Pointcut("@annotation(com.zbkj.front.config.PreventDuplicate)")
    public void pointCut(){}

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Around("pointCut()")
    public Object aroundPointCut(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        PreventDuplicate preventDuplicateAnnotation = methodSignature.getMethod().getAnnotation(PreventDuplicate.class);
        String value = preventDuplicateAnnotation.value();
        int timeout = preventDuplicateAnnotation.timeout();

        try {
            if(redisTemplate.opsForValue().setIfAbsent(PREFIX + value,"1", Duration.ofSeconds(timeout))){
                return joinPoint.proceed();
            }else{
               return CommonResult.failed(CommonResultCode.ERROR,String.format("请求太频繁，请求间隔需大于%d秒",timeout));
            }
        } finally {
            if(timeout == 0) {
                redisTemplate.delete(PREFIX + value);
            }
        }
    }
}
